// pages/function/upload/upload-batch.js
const APP = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    targetId:0,
    isEdit:false,
    pageinfo:{
        title:'',
        content:'',
    },
    questionList:[],
    isSubmitLoading: false, //提交状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this;

    //控制权限
    APP.appauth.setAuthSetting();
    //初始化数据
    if(options.tid){
        this.setData({
            targetId:options.tid,
            isEdit:options.tid>0,
        },function(){
            _this.doInitPageData(null);
        });
    }else{
        //新增初始化数据
        this.data.questionList.push({problems:'',attachmentList:[],uploadFileObj:{ images:[],videos:[],audios:[],documents:[]},uploadRef:null,});
        this.setData({
            questionList:this.data.questionList
        });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 【逻辑区域】
   */
   //加载数据
    doInitPageData(completedcallback){
        let _this = this;

        APP._post('/Form/infoBatch', {
          id: this.data.targetId,
        }, false, function (resData) {
            //执行成功
            //组装问题数组
            for(let item of resData.problems){
              let tmpArr=[];
              //组装附件数组
              for(let i=0; i<item.attachmentList.length;i++){
                  tmpArr.push({
                      fileType:item.attachmentList[i].fileType,
                      filePath:item.attachmentList[i].filePath,
                      fileName:item.attachmentList[i].fileName,
                      fileUrl:APP.appconfig.fwrootweb + item.attachmentList[i].filePath,
                  });
              }

              _this.data.questionList.push({
                  problems:item.problem,
                  attachmentList:tmpArr, //统一的附件
                  uploadRef:null,
                  uploadFileObj:{ images:[],videos:[],audios:[],documents:[]}
              });
          }
          //不能为空
          if(_this.data.questionList.length<1){
              _this.bindQadd();
          }
          
          _this.setData({
              pageinfo:{
                  title:resData.title,
                  content:resData.content,
              },
              questionList:_this.data.questionList,
          },function(){
              //显示附件
              _this.doShowQuestionAttachment();
          });
        }, function (res) {
            //执行失败
        }, function (res) {
            //执行完成
            completedcallback && completedcallback();
        });
    },
   //提交表单
    bindFrmSubmit(eventhandle){
        let _this = this;
        let formvalues = eventhandle.detail.value;

        if (formvalues.title.length < 1) {
            APP.apptool.showToastInfo('请输入反映标题!');
            return;
        }
        if (formvalues.content.length < 1) {
            APP.apptool.showToastInfo('请详细说明时间地点和反映问题的具体内容!');
            return;
        }

        //问题组检测
        let tmpQuestions = [],tmpIndex=0;
        for(let item of this.data.questionList){
            tmpIndex++;
            if (item.problems.length < 1) {
                APP.apptool.showToastInfo('请输入问题'+(tmpIndex)+'描述!');
                return;
            }else{
                // 转换数据
                let tmpFiles = item.uploadRef.data.getUploadFiles();
                let fileNames=[],filePaths=[],fileTypes=[];
                for(let img of tmpFiles){
                    fileNames.push(img.originalname);
                    filePaths.push(img.pathname);
                    fileTypes.push(img.type);
                }
                let tmpItem = {problems:item.problems,fileNames:fileNames.join(','),filePaths:filePaths.join(','),fileTypes:fileTypes.join(',')};
                tmpQuestions.push(tmpItem);
            }
        }
        
        //禁用操作
        _this.setData({
            isSubmitLoading: true,
        });
        let tmpUrl = (this.data.isEdit?'/Form/submit':'/Form/submit');
        let postData = {
            problemInfo:JSON.stringify(tmpQuestions),
            title:formvalues.title,
            content:formvalues.content,
        };

        //编辑
        if(this.data.isEdit){
            postData.id = this.data.targetId;
        }

        APP._post(tmpUrl,  postData, false, function (resData,res) {
            //执行成功
            APP.apptool.showToastInfo(res.caMsg, null, 2000, function (res) {
              APP.apptool.navigateBackPage(1, function (targetPage) {
                  //需刷新数据面，必须实现refreshPage()方法
                  // targetPage.refreshPage();
              });
          });
        }, function (res) {
            //执行失败
        }, function (res) {
            //执行完成
            //恢复操作
            _this.setData({
                isSubmitLoading: false,
            });
        });
    },
    // 问题绑定
    bindInputQuestion(e){
        let dataset = e.currentTarget.dataset;
        this.data.questionList[dataset.idx].problems = e.detail.value;
    },
    // 新增问题
    bindQadd(e){
        let _this = this;
        //绑定附件
        _this.doBindQuestionAttachment();
        //增加新项
        this.data.questionList.push({problems:'',attachmentList:[],uploadFileObj:{ images:[],videos:[],audios:[],documents:[]},uploadRef:null,});
        this.setData({
            questionList:this.data.questionList
        },function(){
            //显示附件
            _this.doShowQuestionAttachment();
            APP.apptool.pageScrollToBottom('fwcontainer');
        });
    },
    // 删除问题
    bindQdel(e){
        let _this = this;
        let dataset = e.currentTarget.dataset;
        APP.apptool.showModalConfirm('提示', '确认删除问题'+(dataset.idx+1)+'吗？', '放弃', '确认',function(confirm, cancel){
            if(cancel) return;

            _this.data.questionList.splice(dataset.idx,1);
            _this.setData({
                questionList:_this.data.questionList
            },function(){
                //显示附件
                _this.doShowQuestionAttachment();
                APP.apptool.showToastInfo('删除成功!');
            });
        });
    },
     //设置组件引用
     bindUploadReffer(ref){
        let tmpRef = ref.detail;
       // this.data.uploadRef = ref.detail;
       this.data.questionList[tmpRef.data.uploadIndex].uploadRef = ref.detail;
   },
   doGetUploadFile(index){
       if(this.data.questionList[index].uploadRef){
          let tmpFiles = this.data.questionList[index].uploadRef.data.getUploadFiles();
          return tmpFiles;
       }
       return [];
   },
    //加载附件
    doSetUploadFile(ref,attachmentList){
        if(ref){
            ref.data.setUploadFiles(attachmentList);
        }
    },
    //绑定附件
    doBindQuestionAttachment(){
        for(let i=0; i<this.data.questionList.length;i++){
            if(this.data.questionList[i].uploadRef){
                //组装上传文件数组
                let tmpUploadFiles = this.data.questionList[i].uploadRef.data.getUploadFiles();
                console.log('tmpUploadFiles',tmpUploadFiles);
                let tmpArr = [];
                //组装附件数组
                for(let sitem of tmpUploadFiles){
                    tmpArr.push({
                        fileType:sitem.type,
                        filePath:sitem.pathname,
                        fileName:sitem.originalname,
                        fileUrl:sitem.urlname,
                    });
                }
                this.data.questionList[i].attachmentList = tmpArr;
            }
            console.log('questionList',this.data.questionList);
        }
    },
    //刷新附件
    doShowQuestionAttachment(){
        //显示附件
        for(let item of this.data.questionList){
            this.doSetUploadFile(item.uploadRef,item.attachmentList);
        }
    },

})